import { useState, useCallback } from 'react';
import { getDepartmentList, DataModel } from '@/utils/api/student/student';

// 模块级缓存
let cachedDepartmentOptions: string[] = [];
let cachedAllMajorOptions: string[] = [];
let cachedDepartmentMajorMap: Map<string, string[]> = new Map();

export const useDepartmentData = () => {
    const [departmentOptions, setDepartmentOptions] = useState<string[]>(cachedDepartmentOptions);
    const [allMajorOptions, setAllMajorOptions] = useState<string[]>(cachedAllMajorOptions);
    const [departmentMajorMap, setDepartmentMajorMap] = useState<Map<string, string[]>>(cachedDepartmentMajorMap);
    const [loading, setLoading] = useState(false);

    // 获取所有院系和专业数据
    const fetchAllData = useCallback(async () => {
        if (cachedDepartmentOptions.length > 0 && cachedAllMajorOptions.length > 0) {
            setDepartmentOptions(cachedDepartmentOptions);
            setAllMajorOptions(cachedAllMajorOptions);
            setDepartmentMajorMap(cachedDepartmentMajorMap);
            return;
        }

        try {
            setLoading(true);
            const response = await getDepartmentList();
            if (response.code === 200) {
                // 提取所有不重复的院系
                const departments = Array.from(
                    new Set(response.data.map((item: DataModel) => item.department))
                );
                setDepartmentOptions(departments);
                cachedDepartmentOptions = departments;

                // 提取所有不重复的专业
                const allMajors = Array.from(
                    new Set(response.data.map((item: DataModel) => item.major))
                );
                setAllMajorOptions(allMajors);
                cachedAllMajorOptions = allMajors;

                // 构建院系-专业映射
                const map = new Map<string, string[]>();
                response.data.forEach((item: DataModel) => {
                    if (!map.has(item.department)) {
                        map.set(item.department, []);
                    }
                    map.get(item.department)!.push(item.major);
                });
                setDepartmentMajorMap(map);
                cachedDepartmentMajorMap = map;
            }
        } catch (error) {
            console.error('获取院系专业数据失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    return {
        departmentOptions,
        allMajorOptions,
        departmentMajorMap,
        loading,
        fetchAllData
    };
};